package ai_role_api

import (
	"errors"
	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
	"muziai-server/global"
	"muziai-server/models"
	"muziai-server/utils/jwts"
	"muziai-server/utils/res"
)

type RoleCreateRequest struct {
	Title    string `json:"title" binding:"required"`
	Avatar   string `json:"avatar"`
	Category string `json:"category"` // 角色分类
	Abstract string `json:"abstract" binding:"required"`
	Prompt   string `json:"prompt" binding:"required"` // 提示词
}

func (air AiRoleApi) RoleCreateView(c *gin.Context) {
	var cr RoleCreateRequest
	err := c.ShouldBindJSON(&cr)
	if err != nil {
		res.FailWithError(c, err)
		return
	}

	var model models.AiRoleModel

	_claims, _ := c.Get("claims")
	claims := _claims.(*jwts.Claims)

	err = global.DB.Take(&model, "user_id = ? and title = ?", claims.UserID, cr.Title).Error
	if err == nil {
		res.FailWithMsg(c, "同一个用户不能创建相同名称的角色")
		return
	}

	err = global.DB.Transaction(func(tx *gorm.DB) error {

		err = air.userservice.UserScope(tx, claims.UserID, -global.Config.AI.CreateRoleScope)
		if err != nil {
			return err
		}
		// 创建角色
		err = tx.Create(&models.AiRoleModel{
			Title:    cr.Title,
			Avatar:   cr.Avatar,
			UserID:   claims.UserID,
			Category: cr.Category,
			Abstract: cr.Abstract,
			Prompt:   cr.Prompt,
		}).Error
		if err != nil {
			return errors.New("角色记录创建失败")
		}
		return nil
	})
	if err != nil {
		res.FailWithError(c, err)
		return
	}
	res.OkWithMsg(c, "创建角色成功")
}
